package com.pth.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.pth.dao.ZhinanDAO;
import com.pth.model.Zhinan;

public class ZhinanDAOImpl implements ZhinanDAO {

	private HibernateTemplate hibernateTemplate;
	
	public void add(Zhinan zhinan) {

		hibernateTemplate.save(zhinan);
		
	}

	public void delete(Zhinan zhinan) {

		hibernateTemplate.delete(zhinan);
		
	}

	public int getAllNum() {

		String hqlString="from Zhinan z";
		return hibernateTemplate.find(hqlString).size();
		
	}

	public Zhinan getZhinanByid(int id) {

		return hibernateTemplate.get(Zhinan.class, id);
		
	}


	@SuppressWarnings("unchecked")
	public List<Zhinan> getZhinans(final int pagesize,final int offset) {

		final String hqlString="from Zhinan z order by z.publishtime desc";
		
		List<Zhinan> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
	
	}

	public void update(Zhinan zhinan) {


		hibernateTemplate.update(zhinan);

	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@SuppressWarnings("unchecked")
	public List<Zhinan> getZhinansOrderByScannum(final int pagesize,final int offset) {

		final String hqlString="from Zhinan z order by z.scannum desc";
		
		List<Zhinan> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
	}

	public List<Zhinan> getAllZhinans() {
		return hibernateTemplate.find("from Zhinan");
	}

}
